import { Observable, Subscription } from 'rxjs';
import { Injectable } from '@angular/core';

/**
 * 实现定时调用某一函数的功能
 * timerRenovating：定时调用函数
 * **initialDelay：延迟触发时间
 * **period：触发某一功能的时间间隔
 * **fun：被触发的功能
 * **...args：被触发功能函数的时间间隔
 * 
 * destroyTimer：销毁定时器
 * **
 * Note：为了提高性能，建议在component的OnDestroy函数里调用destroyTimer
 * 
 * @export
 * @class WorkerService
 */
@Injectable()
export class WorkerService {

    private subObject: Subscription;

    timerRenovating(initialDelay: number, period: number, fun: Function, ...args) {
        if (fun !== undefined || fun !== null) {
            let timer = Observable.timer(initialDelay, period);
            if(args.length > 0){
                this.subObject = timer.subscribe(()=>fun.apply(null,args));
            }
        }
    }

    destroyTimer() {
        if (this.subObject !== undefined)
            this.subObject.unsubscribe();
    }

} 